<script setup lang="ts">
import { ref, onMounted, computed } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"

import { listPets } from "@/api/pets"
import { listPetWeight, addPetWeight, updatePetWeight, deletePetWeight, emptyPetWeight, type PetWeight } from "@/api/pet_weight"

const pets = ref<any[]>([])
const currentPetId = ref<number | null>(null)

const weightList = ref<PetWeight[]>([])
const loading = ref(false)

const addDialog = ref(false)
const editDialog = ref(false)

const form = ref(emptyPetWeight())

/* 当前选中的宠物（用于卡片显示） */
const currentPet = computed(() => {
    return pets.value.find(p => p.id === currentPetId.value) || null
})

/* 加载宠物列表 */
const loadPets = async () => {
    const res = await listPets({ pageNum: 1, pageSize: 100 })
    pets.value = res.data.list
    if (pets.value.length > 0) {
        currentPetId.value = pets.value[0].id
    }
}

/* 加载体重记录 */
const loadWeightList = async () => {
    if (!currentPetId.value) return
    loading.value = true
    const res = await listPetWeight(currentPetId.value)
    weightList.value = res.data || []
    // console.log("weightList: {}", weightList.value);
    loading.value = false
}

/* 切换宠物 */
const changePet = (id: number) => {
    currentPetId.value = id
    loadWeightList()
}

/* 打开新增 */
const openAdd = () => {
    form.value = emptyPetWeight();
    form.value.petId = currentPetId.value || 0
    addDialog.value = true
}

/* 保存新增 */
const saveAdd = async () => {
    const res = await addPetWeight(form.value)
    if (res.code === 200) {
        ElMessage.success("添加成功")
        addDialog.value = false
        loadWeightList()
    } else {
        ElMessage.error(res.msg)
    }
}

/* 编辑记录 */
const openEdit = (row: any) => {
    form.value = { ...row }
    form.value.petId = currentPetId.value || 0
    editDialog.value = true
}

/* 保存编辑 */
const saveEdit = async () => {
    const res = await updatePetWeight(form.value)
    if (res.code === 200) {
        ElMessage.success("修改成功")
        editDialog.value = false
        loadWeightList()
    } else {
        ElMessage.error(res.msg)
    }
}

/* 删除记录 */
const removeRecord = (row: any) => {
    ElMessageBox.confirm("确定删除该记录吗？", "提示", { type: "warning" })
        .then(async () => {
            const res = await deletePetWeight(row.id, currentPetId.value || 0)
            if (res.code === 200) {
                ElMessage.success("删除成功")
                loadWeightList()
            } else {
                ElMessage.error(res.msg)
            }
        })
}

onMounted(async () => {
    await loadPets()
    await loadWeightList()
})
</script>

<template>
<div class="page">

    <!-- 上方宠物下拉选择 -->
    <div class="pet-selector-row">
        <el-select
            v-model="currentPetId"
            filterable
            placeholder="选择宠物"
            @change="changePet"
            style="width: 260px"
        >
            <el-option
                v-for="p in pets"
                :key="p.id"
                :value="p.id"
                :label="p.name"
            >
                <div class="option-item">
                    <img :src="p.avatar" class="option-avatar" />
                    <span>{{ p.name }}</span>
                </div>
            </el-option>
        </el-select>
    </div>

    <!-- 标题 + 当前宠物卡片 + 新增按钮 -->
    <div class="header">
        <!-- 左侧：标题 + 当前宠物卡片（纵向排列） -->
        <div class="header-left">
            <span class="title">体重记录</span>

            <div v-if="currentPet" class="current-pet-card">
                <img :src="currentPet.avatar" class="card-avatar" />
                <span class="card-name">{{ currentPet.name }}</span>
            </div>
        </div>

        <!-- 右侧：新增按钮 -->
        <div>
        <el-button class="add-record" type="primary" @click="openAdd">新增记录</el-button>
        </div>
        
    </div>

    <!-- 列表 -->
    <el-table :data="weightList" v-loading="loading" z>
        <el-table-column prop="weight" label="体重(kg)" width="120" />
        <el-table-column prop="recordDate" label="记录日期" width="180" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="160">
            <template #default="{ row }">
                <el-button link type="primary" @click="openEdit(row)">编辑</el-button>
                <el-button link type="danger" @click="removeRecord(row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <div style="height:20px;"></div>

    <!-- 新增弹窗 -->
    <el-dialog v-model="addDialog" title="新增体重记录" width="420px">
        <el-form :model="form" label-width="90px">
            <el-form-item label="体重(kg)">
                <el-input-number v-model="form.weight" :min="0.1" :max="200" />
            </el-form-item>

            <el-form-item label="记录日期">
                <el-date-picker v-model="form.recordDate" type="date" value-format="YYYY-MM-DD" />
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="form.remark" clearable />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="addDialog = false">取消</el-button>
            <el-button type="primary" @click="saveAdd">保存</el-button>
        </template>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialog" title="编辑体重记录" width="420px">
        <el-form :model="form" label-width="90px">
            <el-form-item label="体重(kg)">
                <el-input-number v-model="form.weight" :min="0.1" :max="200" />
            </el-form-item>

            <el-form-item label="记录日期">
                <el-date-picker v-model="form.recordDate" type="date" value-format="YYYY-MM-DD" />
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="form.remark" clearable />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="editDialog = false">取消</el-button>
            <el-button type="primary" @click="saveEdit">保存</el-button>
        </template>
    </el-dialog>

</div>
</template>

<style scoped>
.page {
    padding: 10px;
}

/* 顶部宠物下拉选择 */
.pet-selector-row {
    display: flex;
    align-items: center;
    gap: 20px;
    padding-bottom: 20px;
    margin-bottom: 10px;
}

.option-item {
    display: flex;
    align-items: center;
    gap: 10px;
}

.option-avatar {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    object-fit: cover;
}

/* 标题 + 卡片 + 按钮 */
.header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 15px;
}

/* 左侧：标题 + 卡片 纵向排列 */
.header-left {
    display: flex;
    flex-direction: row;
    gap: 15px;
}

.title {
    font-size: 20px;
    font-weight: 600;
}

/* 当前宠物卡片：沿用之前 tab 的样式 */
.current-pet-card {
    display: flex;
    align-items: center;
    gap: 10px;
    background: #fff;
    padding: 8px 16px;
    border-radius: 12px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.06);
    border: 2px solid #409EFF;
    width: 160px;
}

.card-avatar {
    width: 38px;
    height: 38px;
    border-radius: 8px;
    object-fit: cover;
}

.card-name {
    font-size: 15px;
    font-weight: 600;
    color: #333;
}

/* 右侧按钮 */
.add-record {
    align-self: center;
}
</style>
